package com.ec.auth.security.config;

import com.ec.auth.security.filter.AdminUsernamePasswordAuthenticationFilter;
import com.ec.auth.security.filter.JwtAuthenticationTokenFilter;
import com.ec.auth.security.handle.FailHandle;
import com.ec.auth.security.handle.SuccessHandle;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.SecurityConfigurerAdapter;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.web.DefaultSecurityFilterChain;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

@Configuration
public class SecurityAdminConfig extends SecurityConfigurerAdapter<DefaultSecurityFilterChain, HttpSecurity> {

    @Autowired
    private FailHandle failHandle;

    @Autowired
    private SuccessHandle successHandle;

    /**
     * jwt 认证过滤器
     */
    @Autowired
    private JwtAuthenticationTokenFilter jwtAuthenticationTokenFilter;

    @Override
    public void configure(HttpSecurity builder) {
        // 自定义身份验证过滤器
        AdminUsernamePasswordAuthenticationFilter adminUsernamePasswordAuthenticationFilter = new AdminUsernamePasswordAuthenticationFilter();
        // 设置身份验证类--每个过滤器链都要设置
        adminUsernamePasswordAuthenticationFilter.setAuthenticationManager(builder.getSharedObject(AuthenticationManager.class));
        // 设置认证失败异常类
        adminUsernamePasswordAuthenticationFilter.setAuthenticationFailureHandler(failHandle);
        // 设置认证成功类
        adminUsernamePasswordAuthenticationFilter.setAuthenticationSuccessHandler(successHandle);
        // 身份验证失败类

        builder.addFilterAt(adminUsernamePasswordAuthenticationFilter, UsernamePasswordAuthenticationFilter.class)
                // 加载
                .addFilterBefore(jwtAuthenticationTokenFilter, AdminUsernamePasswordAuthenticationFilter.class);
    }
}
